import * as Router from 'vue-router'
import store from '@/store'
import routerMap from './routerMap'
import routerElementMap from './routerElementMap'
import { getAdminToken, setAdminToken } from "@/utils/storages"

let routes = [
    {
        path: '/login',
        name: 'pageLogin',
        hidden: true,
        component: () => import('@/views/admin/login/index.vue')
    },
    {
        path: '/refresh',
        name: 'refresh',
        hidden: true,
        component: () => import('@/views/refresh.vue')
    },
    {
        path: '/:catchAll(.*)',
        name: 'page404',
        hidden: true,
        component: () => import('@/views/404.vue')
    }
]

export const asyncRouterMap = routerMap
export const constantElementMap = routerElementMap
export const constantRouterMap = routes

// routes = routes.concat(routerMap)

const vueRouter = Router.createRouter({
    history: Router.createWebHashHistory(),
    routes: constantRouterMap
})

const whiteList = ['/login'] // 不重定向白名单

vueRouter.beforeEach(async (to, from, next) => {
    if (getAdminToken()) {
        let isRequestApi = import.meta.env.VITE_APP_IsRequestApi
        if (!isRequestApi || isRequestApi === "true") {
            // 正式请求api
            await toRouterBeforeEach(to, from, next)
        } else {
            // 本地浏览数据
            await toLocalRouterBeforeEach(to, from, next)
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next({ path: '/login' })
        }
    }
})
// 本地浏览数据
const toLocalRouterBeforeEach = async (to, from, next) => {
    // 没有角色设置test，并添加路由表
    if (to.path === '/login') {
        next({ path: '/' })
    } else {
        if (store.getters.roles.length === 0) {
            // 根据roles权限生成可访问的路由表
            store.commit('setRoles', ["AbpIdentity.Roles"])
            await store.dispatch('setLocalRouters').then(() => { 
                // 动态添加可访问路由表
                let curRouter = routes.concat(store.getters.addRouters)
                addRouters(curRouter)
                // hack方法 确保addRoutes已完成
                next({ path: to.path, replace: true })
            })
        } else {
            // 没有动态改变权限的需求可直接next()
            if (hasPermission(store.getters.roles, to.meta.roles)) {
                next()
            } else {
                next({ name: 'page404', replace: true })
            }
        }
    }
}
// 正式请求api
const toRouterBeforeEach = async (to, from, next) => {
    if (to.path === '/login') {
        next({ path: '/' })
    } else {
        if (store.getters.roles.length === 0) {
            // 拉取用户信息
            await store.dispatch('getUserInfo').then(res => { 
                // 拉取用户信息，返回路由表
                const roles = res.extraProperties.permissions
                // 根据roles权限生成可访问的路由表
                store.dispatch('setRouters', { roles, userName: res.userName }).then(() => { 
                    // 动态添加可访问路由表
                    let curRouter = routes.concat(store.getters.addRouters)
                    addRouters(curRouter)
                    console.log(store.getters.addRouters)
                    // hack方法 确保addRoutes已完成
                    next({ path: to.path, replace: true })
                })
            }).catch((err) => {
                store.dispatch('loginOut').then(() => {
                    window.$Common.errorMsg(err || '获取信息出错，请重新登录!')
                    location.reload()
                })
            })
        } else {
            // 没有动态改变权限的需求可直接next()
            if (hasPermission(store.getters.roles, to.meta.roles)) {
                next()
            } else {
                next({ name: 'page404', replace: true })
            }
        }
    }
}

// 验证权限
const hasPermission = (roles, permissionRoles) => {
    if (!permissionRoles) return true
    return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

// 动态添加可访问路由表
const addRouters = (routers) => {
    for (let i in routers) {
        const item = routers[i]
        vueRouter.addRoute(item)
    }
}

export default vueRouter
